import http.server
import socketserver

import io
import html
import datetime
import os,sys

sys_argv=sys.argv

PORT=sys_argv[1] if 1 < len(sys_argv) else 5188
DIRECTORY=sys_argv[2] if 2 < len(sys_argv) else os.getcwd()
# PORT = 8000
#DIRECTORY = "E:\\"  # 替换为您要共享的目录路径
os.chdir(DIRECTORY)  # 设置工作目录为指定目录

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def list_directory(self, path):
        try:
            file_list = os.listdir(path)
        except OSError:
            self.send_error(404, "No permission to list directory")
            return None
        file_list.sort(key=lambda a: a.lower())

        r = []
        display_path = http.server.html.escape(self.path)
        title = 'Directory listing for %s' % display_path
        r.append('<!DOCTYPE html>')
        r.append('<html><head>')
        r.append(f'<title>{title}</title>')
        r.append('</head><body>')
        r.append(f'<h2>{title}</h2>')
        r.append('<hr>')
        r.append('<table style="width:100%; border-collapse: collapse; margin-top: 0px; margin-bottom: 0px;">')
        r.append(
            '<tr><th style="text-align: left; padding: 4px; border: 1px solid white;">Name</th><th style="text-align: left; padding: 4px; border: 1px solid white;">Size</th><th style="text-align: left; padding: 4px; border: 1px solid white;">Last Modified</th></tr>')

        for file_name in file_list:
            file_path = os.path.join(path, file_name)
            size = os.path.getsize(file_path)
            if size < 1024:  # 如果文件大小小于1KB，直接以B为单位显示
                size_str = f"{size} B"
            elif size < 1024 * 1024:  # 如果文件大小小于1MB，以KB为单位显示
                size_str = f"{size / 1024:.2f} KB"
            elif size < 1024 * 1024 * 1024:  # 如果文件大小小于1GB，以MB为单位显示
                size_str = f"{size / (1024 * 1024.0):.2f} MB"
            else:  # 大于1GB，以GB为单位显示
                size_str = f"{size / (1024 * 1024 * 1024.0):.2f} GB"

            mtime = os.path.getmtime(file_path)
            mtime_str = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')  # 格式化修改时间
            link = f'<a href="{file_name}">{file_name}</a>'
            r.append(
                f'<tr><td style="text-align: left; padding: 4px; border: 1px solid white;">{link}</td><td style="text-align: left; padding: 4px; border: 1px solid white;">{size_str}</td><td style="text-align: left; padding: 4px; border: 1px solid white;">{mtime_str}</td></tr>')

        r.append('</table>')
        r.append('</body></html>')
        encoded = '\n'.join(r).encode('utf-8', 'surrogateescape')
        f = io.BytesIO()
        f.write(encoded)
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        return f


with socketserver.TCPServer(("", int(PORT)), MyHttpRequestHandler) as httpd:
    print(f'Specify Port: "fileServices.exe 5188"')
    print(f'Specify Port and directory: "fileServices.exe 5188 C:\directory"')
    print(f'')
    print(f"Mapping directory: {DIRECTORY}")
    print(f'')
    print(f"Access address: http://127.0.0.1:{PORT}")
    print(f"Access address: http://localhost:{PORT}")
    print(f'')
    httpd.serve_forever()
